package com.xzy.scheduling.service.b;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 说明：使用自定义的线程池处理定时任务
 *
 * @author xzy
 * @date 2022/12/8  21:28
 */
@Slf4j
//@Service
//@Configuration
public class MyScheduledService implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        // 自定义线程池
        ExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(4);
        scheduledTaskRegistrar.setScheduler(scheduledExecutorService);
    }

    /**
     * Task1：每隔1秒处理一次，处理时长10秒
     */
    @Scheduled(cron = "0/1 * * * * ? ")
    public void task1() {
        log.info("Task1：start");
        aLongTimeTask(10000);
        log.info("Task1：end\n");
    }

    /**
     * Task2：每隔1秒处理一次，处理时长1秒
     */
    @Scheduled(cron = "0/1 * * * * ? ")
    public void task2() {
        log.info("Task2：start");
        aLongTimeTask(1000);
        log.info("Task2：end\n");
    }

    private void aLongTimeTask(long time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
